﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using TSOL.FastSPWeb.ValueObjects;

namespace TSOL.FastSPWeb.Core
{
    internal class SiteDictionaryHelper
    {
        static void HandleSite(SPSite Site, Dictionary<string, Guid> webDict)
        {
            foreach (SPWeb _web in Site.AllWebs)
            {
                try
                {
                    if (!webDict.ContainsKey(_web.ServerRelativeUrl))
                    {
                        webDict.Add(_web.ServerRelativeUrl, _web.ID);
                    }
                }
                finally
                {
                    _web.Dispose();
                }
            }
        }

        static void HandleWeb(SPWeb Web, Dictionary<string, Guid> webDict)
        {
            foreach (SPWeb _web in Web.Webs)
            {
                try
                {
                    if (!webDict.ContainsKey(_web.ServerRelativeUrl))
                    {
                        webDict.Add(_web.ServerRelativeUrl, _web.ID);
                        if (_web.Webs.Count > 0)
                            HandleWeb(_web, webDict);
                    }
                }
                finally
                {
                    _web.Dispose();
                }
            }
        }

        internal static void Build(SPSite _Site) {
            lock (FastSPWebThreadWorkerQueue.GlobalSPWebThreadWorkerQueue.SiteDictionary)
            {
                foreach (SPSite _site in _Site.WebApplication.Sites)
                {
                    try
                    {
                        SPSiteEntryClass _entry = null;
                        int _urlHashCode = _site.Url.GetHashCode();
                        if (!FastSPWebThreadWorkerQueue.GlobalSPWebThreadWorkerQueue.SiteDictionary.ContainsKey(_urlHashCode))
                        {
                            _entry = new SPSiteEntryClass();
                            _entry.SiteID = _site.ID;
                            _entry.WebDictionary = new System.Collections.Generic.Dictionary<string, Guid>();
                            FastSPWebThreadWorkerQueue.GlobalSPWebThreadWorkerQueue.SiteDictionary.Add(_urlHashCode, _entry);
                        }
                        else
                        {
                            FastSPWebThreadWorkerQueue.GlobalSPWebThreadWorkerQueue.SiteDictionary.TryGetValue(_urlHashCode, out _entry);
                        }
                        HandleSite(_site, _entry.WebDictionary);
                    }
                    finally
                    {
                        _site.Dispose();
                    }
                }
            }

        }
    }
}
